package com.cqhz.quwan.util

import android.graphics.Bitmap
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

fun Bitmap.saveImage(path:String,fileName:String,ok:((String)->Unit)?=null){
    val appDir = File(Environment.getExternalStorageDirectory().absolutePath,path)
    if (!appDir.exists()){
        appDir.mkdirs()
    }
    val fileExt = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length).toUpperCase()
    val imageFormat = when(fileExt){
        "JPG","JPEG"-> Bitmap.CompressFormat.JPEG
        "PNG" -> Bitmap.CompressFormat.PNG
        else -> throw IllegalArgumentException("非法图片格式")
    }
    val imageFile = File(appDir,fileName)
    var fos:FileOutputStream? = null
    try {
        fos = FileOutputStream(imageFile)
        this.compress(imageFormat,100,fos)
        fos.flush()
        ok?.invoke(imageFile.absolutePath)
    }catch (e:IOException){
        e.printStackTrace()
    }finally {
        try {
            fos?.close()
        }catch (e:IOException){
            e.printStackTrace()
        }
        if (this.isRecycled){
            System.gc()
        }
    }

}